<?php
namespace control;
/*
*收票类
*/

class receiveInvoiceClass extends adIndexClass
{
    private const page = 'receiveInvoice';
    private const table = 'invoice_open';
    private const table_mx = 'invoice_open_detail';
    private const title = '收票';
    private string $addIco = root . 'img/control/v_add.svg';
    private string $delIco = root . 'img/control/v_del.svg';

    /*列表-查询条件*/
    public function home()
    {
        return $this->room();
    }


    /**
     * 计算税额
     */
    public function calculateTax($isTax,$money,$tax=0): float
    {
        if ($isTax){
            //含税
            $taxMoney = round($money*$tax/(1+$tax),2);
        }else{
            $taxMoney = round($money*$tax,2);
        }
        return $taxMoney;
    }
    /**
     * 编辑
     */
    public function editEdit()
    {
        $href = $this->get('href');
        $id = $this->post('id') ?: self::getId();
        $models = $this->post('model');
        $names = $this->post('name');
        $units = $this->post('unit');
        $nums = $this->post('num');
        $prices = $this->post('price');
        $moneys = $this->post('money') ?: [];
        $taxs = $this->post('tax') ?: [];
        $mxIds = $this->post('mxId');
        $sourceIds = $this->post('sourceId');
        $field = [
            'buyCompany' => $this->post('clientName'),
            'classify'=>$this->post('invoiceType'),
            'buyTaxNo' => $this->post('buyTaxNum'),
            'buyAddress' => $this->post('buyAddress'),
            'buyBank' => $this->post('buyBankName'),
            'checkName' => $this->post('checkName'),
            'receiveName' => $this->post('receiveName'),
            'createName' => $this->post('createName'),
            'invoiceDate' => $this->post('invoiceDate'),
            'invoiceCode' => $this->post('invoiceCode'),
            'invoiceNo' => $this->post('invoiceNo'),
            'secret' => $this->post('secret'),
            'khid' => $this->post('khid'),
            'isTax' => $this->post('isTax'),
            'saleCompany' => $this->post('saleCompany'),
            'saleTaxNo' => $this->post('saleTaxNum'),
            'saleAddress' => $this->post('saleAddress'),
            'saleBank' => $this->post('saleBankName'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'invoiceDate' => L('finance.table.kai_piao_ri_qi'),
            'invoiceCode' => L('finance.table.fa_piao_dai_ma'),
            'invoiceNo' => L('finance.table.fpbh'),
            'buyCompany' => L('finance.table.ghdwmc'),
            'buyTaxNo' => L('finance.table.ghdwnsrsbh'),
            'saleCompany' => L('finance.table.xhdw'),
            'saleTaxNo' => L('finance.table.xhdwnsrsbh'),
        ];
        $rules = [
            'invoiceDate' => 'required',
            'invoiceCode' => 'required',
            'invoiceNo' => 'required',
            'buyCompany' => 'required',
            'buyTaxNo' => 'required',
            'saleCompany' => 'required',
            'saleTaxNo' => 'required',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power('receiveInvoice', "edit") && !$this->power('incomeInvoice', "edit")) {
            $json['warn'] = L('finance.table.receivePermission');
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = L('finance.table.qtxfpnr');
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and type = '收票' and invoiceNo = '$field[invoiceNo]' and id !='$id'")) > 0) {
            $json['warn'] = L('finance.table.yczcfp');
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'type' => '收票',
                    'createName' => $this->control['name'],
                    'state'=>'正常',
                    'stid'=>self::$stid
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            $totalMoney = $taxTotalMoney = 0;
            $ids = [];
            foreach ($mxIds as $k => $mxId) {
                if ($names[$k]) {
                    $prices[$k] = $prices[$k]?round($prices[$k],openInvoiceClass::priceDecimal()):0;
                    $detail = query(self::table_mx, "id = '$mxId'");
                    $ids[] = $mxId;
                    if (empty($moneys[$k]) || !is_numeric($moneys[$k])) {
                        $json['warn'] = str_replace(['{{x}}'], [$k + 1], L('finance.table.openInvoice_edit_warn'));
                        break;
                    }
                    $baseUnit = currencyClass::calculateDecimal($prices[$k]);
                    $taxMoney = $this->calculateTax($field['isTax'],$moneys[$k],$taxs[$k]/100);
                    if (empty($detail['id'])) {
                        $warn = static::insert(array(
                            'table' => self::table_mx,
                            'field' => [
                                'id' => $mxId,
                                'coid' => self::$coid,
                                'orderId' => $id,
                                'name' => $names[$k],
                                'model' => $models[$k],
                                'unit' => $units[$k],
                                'price' => $prices[$k] * $baseUnit,
                                'baseUnit' => $baseUnit,
                                'num' => $nums[$k],
                                'money' => $moneys[$k],
                                'tax' => $taxs[$k]/100,
                                'taxMoney' => $taxMoney,
                                'sourceId'=>$sourceIds[$k],
                                'sourceTable'=>'sale_send_order_detail'
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::table_mx,
                            'field' => [
                                'name' => $names[$k],
                                'model' => $models[$k],
                                'unit' => $units[$k],
                                'price' => $prices[$k] * $baseUnit,
                                'baseUnit' => $baseUnit,
                                'num' => $nums[$k],
                                'money' => $moneys[$k],
                                'tax' => $taxs[$k]/100,
                                'taxMoney' =>$taxMoney,
                                'sourceId'=>$sourceIds[$k],
                                'sourceTable'=>'sale_send_order_detail'
                            ],
                            'where' => "id = '$detail[id]'"
                        ));
                    }
                    $taxTotalMoney += $taxMoney;
                    $totalMoney += $moneys[$k];
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            $unTaxMoney = $field['isTax'] ? ($totalMoney - $taxTotalMoney) : $totalMoney;
            $totalMoney = !$field['isTax'] ? ($totalMoney + $taxTotalMoney) : $totalMoney;
            $warn = update(array('table' => self::table, 'field' => ['money' => $totalMoney, 'unTaxMoney' => $unTaxMoney, 'taxMoney' => $taxTotalMoney], 'where' => "id = '$id'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
            }
            //附件
            $fileIdArr = $this->post('fileId');
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::table_mx, "where" => "id not in ('" . implode("','", $ids) . "') and orderId = '$id'"));
                //添加日志
                $text =  str_replace(['{{staffName}}', '{{invoiceNo}}', '{{id}}'], [$this->control['name'], $field['invoiceNo'], $id], L('finance.table.receiveInvoice_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                if ($href == 'new') {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&id=" . $id;
                }
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 发票OCR识别
     */
    public function vatInvoiceOCR()
    {
        $cla = self::page;
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('finance.table.shuo_ming') => "
                <p>1、".L('finance.table.photosTextOne')."</p>
                <p>2、".L('finance.table.photosTextTwo')."</p>
                "
            ),
            array(
                L('finance.table.pai_zhao')=>"<span class='spanButton' style='margin: 0' onclick='photograph()'>".L('finance.table.original')."</span><span id='photoFile'></span>"
            ),
            array(
                L('finance.table.fjsc')=>fileUploadClass::singleUpload("{$cla}VatInvoiceOCRForm",self::page,'', '发票原件')
            ),
        )
        ));
        //返回
        return $this->layer(array(
            "title" => L('finance.table.scwj'),
            "height" => 315,
            "width" => 800,
            "html" => $html,
            'button' => "<input onclick=\"vatInvoiceOCR('{$cla}VatInvoiceOCRForm',root+'control/adIndex.html?cla=openInvoice&fun=vatInvoiceOCREdit')\" type='button' class='button' value='".L('finance.table.shi_bie')."'>"
        ));
    }

    /**
     * 开票
     * @return string
     */
    public function room(): string
    {
        $id = $this->get('id');
        $page = self::page;
        $info = query(self::table, "id = '$id'");
        $recordDate = text(array('name' => 'invoiceDate', 'class' => 'height23', 'laydate' => [], 'value' => $info['invoiceDate'] ?: $this->date));
        $originalFile ='';
        $originalScript = L('finance.table.originalScript');
        if ($info['id']){
            $originalFile = <<<eof
<span style="padding: 2px;margin-right: 10px" class="del-row-button right" onclick="layer('component','fileDetail',{id:'$id',type:'发票原件'})">$originalScript</span>
eof;

        }
        if (!$info['id']){
            //带出账套的发票信息
            $company = query('company',"coid = '".self::$coid."'");

            $info['buyCompany'] = $company['invoiceCompany'];
            $info['buyTaxNo'] = $company['invoiceNo'];
            $info['buyAddress'] = $company['addressAndTel'];
            $info['buyBank'] = $company['bankName'];
        }

        $isTax = $info['isTax'] ? 'checked' : '';
        $ocr =  L('finance.table.ocr');
        $saveAndAdd = L('finance.table.saveAndAdd');
        $saveText = L('finance.table.save');
        $relativeNo = L('finance.table.relativeNo');
        $invoiceCodeText = L('finance.table.fa_piao_dai_ma');
        $openDateText = L('finance.table.kai_piao_ri_qi');
        $invoiceCheck = L('finance.table.invoiceCheck');
        $taxText = L('finance.table.tax');
        $topButton = <<<eof
    <div class="voucher-button">
        <span class="spanButton li-btn-blue-bg" style="margin-left: 0" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=$page&fun=editEdit&href=new')">$saveAndAdd</span>
        <span class="spanButton" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=$page&fun=editEdit&href=save')">$saveText</span>
        <span class="spanButton" onclick="layer('openInvoice','vatInvoiceVerify',$('[name=voucherForm]').serialize())">$invoiceCheck</span>
        <span class="spanButton" onclick="layer('$page','vatInvoiceOCR',{})">$ocr</span>
         <span class="spanButton" onclick="layer('$page','addSendOrder',$('[name=voucherForm]').serialize())">$relativeNo</span>
    </div>
    <div class="input-div">
    {$invoiceCodeText}：<input class="voucherNo" name="invoiceCode" type="text" value="{$info['invoiceCode']}">&nbsp; <span style="margin-left: 20px">{$openDateText}：{$recordDate}</span>
    <span style="margin-left: 20px">NO：<input class="voucherNo" name="invoiceNo" type="text" value="{$info['invoiceNo']}"></span>
    $originalFile
    <span style="padding: 2px;margin-right: 20px" class="right"><label><input name="isTax" $isTax value="1" type="checkbox" />&nbsp;$taxText</label></span>
</div>
eof;

        $dataTr = '';
        $all = find(array('table' => self::table_mx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($all['array'] as $array) {
            $mxId = $array['id'];
            $array['num'] = floatval($array['num']);
            $array['price'] = currencyClass::intToDecimal($array['price'],$array['baseUnit']);
            $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'value' => $array['tax'] * 100)) . "</select>";
            $dataTr .= <<<eof
<tr class="tr-data td-data center">
  <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value="$array[sourceId]"><div class="add_v_btn"><img src="{$this->addIco}"></div><input name="name[]" value="{$array['name']}" type="text" class="width_100"></td>
            <td><input name="model[]" value="{$array['model']}" type="text" class="width_100"></td>
            <td><input name="unit[]" value="{$array['unit']}" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" value="{$array['num']}" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" value="{$array['price']}" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" value="{$array['money']}" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly value="{$array['taxMoney']}" type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
eof;
        }
        $all['array'] = $all['array'] ?? [];
        $num = 5 - count($all['array']);
        $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'title' => '', 'value' => '')) . "</select>";
        for ($i = 1; $i <= $num; $i++) {
            $mxId = suiji();
            $dataTr .= <<<eof
      <tr class="tr-data td-data center">
            <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value=""><div class="add_v_btn"><img src="{$this->addIco}"></div><input name="name[]" type="text" class="width_100"></td>
            <td><input name="model[]" type="text" class="width_100"></td>
            <td><input name="unit[]" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]"  readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
eof;
        }

        $info['createName'] = !$info['id'] ? $this->control['name'] : $info['createName'];
        $staffName = "<input name='createName' value=''/>";
        $receiveSelect = "<input name='receiveName' value='{$info['receiveName']}'/>";
        $checkSelect = "<input name='checkName' value='{$info['checkName']}'/>";
        $bigNumber = voucherEditClass::num_to_rmb($info['money']);
        $taxHidden = $info['isTax'] ? '' : 'hide';
        $openInvoice = new openInvoiceClass();
        $info['classify'] = $info['classify']?:'普票';
        $title = $info['classify']=='普票'?L('finance.table.zzsptfp'):L('finance.table.zzszyfp');
        $buyText = L('finance.table.gou_huo_dan_wei');
        $bankText = L('finance.table.bank');
        $taxNumText = L('finance.table.taxNum');
        $nameText = L('finance.table.name');
        $addressTelText = L('finance.table.addressTel');
        $secretCodeText = L('finance.table.secretCode');
        $goodsText = L('finance.table.goods');
        $modelText = L('finance.table.gui_ge_xing_hao');
        $unitText = L('finance.table.dan_wei');
        $numText = L('finance.table.shu_liang');
        $priceText = L('finance.table.dan_jia');
        $moneyText = L('finance.table.jin_e');
        $taxRateText = L('finance.table.shui_lu');
        $taxMoneyText = L('finance.table.shui_e');
        $totalText = L('finance.table.he_ji');
        $taxMoneyTotalText = L('finance.table.taxMoneyTotal');
        $saleCompanyText = L('finance.table.xhdw');
        $lowerCaseText = L('finance.table.lowerCase');
        $remarkText = L('finance.table.text');
        $receiveText = L('finance.table.shou_kuan_ren');
        $checkText = L('finance.table.fu_he_ren');
        $openStaffText = L('finance.table.kai_piao_ren');
        $sealText = L('finance.table.seal');
        $data['html'] = <<<efo
<form name="voucherForm">
<div class="voucher-body">
<div class="voucher-title"><span id="invoiceTitle">$title</span>
<img id="switch_ico" class="switch_ico" src="{$openInvoice->switch_ico}"><input name="invoiceType" type="hidden" value="$info[classify]"></div>
<div class="calendarBody">
{$topButton}
    <table class="voucherTable">
      <tr>
        <td colspan="8">
        <div class="td-title">
            <div class="company-title">$buyText</p></div>
            <div style="height: 30px;padding: 5px">
                <div><span>{$nameText}：</span><input name="clientName" value="{$info['buyCompany']}" type="text" style="width: 380px"></div>
                <div><span>{$taxNumText}：</span><input name="buyTaxNum" value="{$info['buyTaxNo']}" type="text" style="width: 380px"></div>
                <div><span>{$addressTelText}：</span><input name="buyAddress"  value="{$info['buyAddress']}"  type="text" style="width: 380px"></div>
                <div><span>{$bankText}：</span><input name="buyBankName" value="{$info['buyBank']}"  type="text" style="width: 380px"></div>
            </div>
            <div class="company-title-two">$secretCodeText</p></div>
            <div style="padding: 5px 5px 0 5px"><textarea name="secret" style="width: 380px;height: 80px">{$info['secret']}</textarea></div>
        </div>
        </td>
        </tr>
        <tr class="tr-data center">
            <td style="width: 221px">$goodsText</td>
            <td style="width: 120px">$modelText</td>
            <td>$unitText</td>
            <td>$numText</td>
            <td style="width: 95px">$priceText<span class="$taxHidden isTax">($taxText)</span></td>
            <td style="width: 95px">$moneyText<span class="$taxHidden isTax">($taxText)</span></td>
            <td>$taxRateText%</td>
            <td style="width: 95px">$taxMoneyText</td>
        </tr>
      {$dataTr}
      <tr class="tr-data tr-border">
            <td>$totalText</td>
            <td colspan="7"><div style="text-align: left">{$moneyText}：<span id="sumMoney">{$info['unTaxMoney']}</span><span class="right">{$taxMoneyText}：<span id="sumTaxMoney">{$info['taxMoney']}</span></span></div></td>
      </tr>
      <tr class="tr-data">
            <td>$taxMoneyTotalText</td>
            <td colspan="7"><div style="text-align: left"><span id="bigNumber">$bigNumber</span><span class="right">{$lowerCaseText}：<span id="sumTaxAndMoney">{$info['money']}</span></span></div></td>
      </tr>
     <tr>
        <td colspan="8">
        <div class="td-title">
            <div class="company-title">$saleCompanyText</div>
            <div style="height: 30px;padding: 5px">
                <div><span>{$nameText}：</span><input name="saleCompany" value="{$info['saleCompany']}" type="text" style="width: 380px"><input name="khid" value="{$info['khid']}" type="hidden"></div>
                <div><span>{$taxNumText}：</span><input name="saleTaxNum" value="{$info['saleTaxNo']}"  type="text" style="width: 380px"></div>
                <div><span>{$addressTelText}：</span><input name="saleAddress" value="{$info['saleAddress']}"  type="text" style="width: 380px"></div>
                <div><span>{$bankText}：</span><input name="saleBankName" value="{$info['saleBank']}"  type="text" style="width: 380px"></div>
            </div>
            <div class="company-title-two" style="letter-spacing: 15px">$remarkText</div>
            <div style="padding: 5px 5px 0 5px"><textarea name="text" style="width: 380px;height: 80px">{$info['text']}</textarea></div>
        </div>
        </td>
        </tr>
    </table>
    <div class="staffName"><span>{$receiveText}：{$receiveSelect}</span><span style="margin-left: 50px">{$checkText}：{$checkSelect}</span><span style="margin-left: 50px">{$openStaffText}：{$staffName}</span><span class="right" style="margin-right: 60px">{$sealText}</span></div>
</div>
</div>
<input name="id" value="$id" type="hidden">
<div id="file-list" class="hide file-list"></div>
</form>
efo;
        $data['html'] .= $this->css() . $this->js();
        //返回
        return $this->tab($data);
    }


    public function js(): string
    {
        $openObj = new openInvoiceClass();
        $openObj->cla=self::page;
        $js = $openObj->js();
        $cla = self::page;
        $js.=<<<eof
<script>
   $("input[name='saleCompany']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=$cla&fun=getSupplier',
        callback:function(data,e){
            $(e).siblings("[name='khid']").val(data.id);
            $("[name='saleTaxNum']").val(data.companyNum);
            $("[name='saleAddress']").val(data.companyBank+data.companyBankNum);
            $("[name='saleBankName']").val(data.companyAddress);
        }
    });
 function saveFile(formName){
    let html = '';
    let val = $("form[name='"+formName+"'] [name='fileId']").val();
    if(val){
            html+="<input name='fileId[]' type='hidden' value='"+val+"'>";
    }
    val = $("form[name='"+formName+"'] [name='photoFileId']").val();
     if(val){
            html+="<input name='fileId[]' type='hidden' value='"+val+"'>";
        }
    $("#file-list").empty().append(html);
   $('#receiveInvoiceVatInvoiceOCR').hide()
    }
function vatInvoiceOCR(form,url){
     //防止高频点击
        let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
         saveFile(form)
        //异步提交数据
        $.post(url, serialize, function (data) {
            if (data.warn == 2) {
               $('#openInvoiceVatInvoiceOCR').hide();
                $(".voucherTable .td-data").remove();
                $(".voucherTable tr").eq(1).after(data.data.html);
                $("[name='receiveName']").val(data.data.info.receiveName);
                $("[name='checkName']").val(data.data.info.checkName);
                $("[name='secret']").val(data.data.info.secret1+data.data.info.secret2+data.data.info.secret3+data.data.info.secret4)
                setVal(data)
               
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
}
 function addRow(){
        $.post(root+'control/adIndex.html?cla=receiveInvoice&fun=addSendOrderEdit',$("form[name='saleSendOrderForm']").serialize(),function(res) {
               $('#receiveInvoiceAddSendOrder').hide()
                $(".voucherTable .td-data").each(function() {
                    if(!$(this).find("[name='name[]']").val()){
                        $(this).remove()
                    }
                })
                $(".voucherTable tr").eq(1).after(res.html);
                 calculateTotal();
            },'json');
        }
</script>
eof;
        return $js;
    }

    /**
     * 模糊查询供应商
     */
    public function getSupplier()
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or code like '%" . $val . "%')";
        $all = find(array('table' => 'supplier', 'where' => "coid = '" . self::$coid . "' and state = '启用' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['name'],'companyAddress'=>$val['registeredAddress'],'companyBank'=>$val['bankName'],'companyBankNum'=>$val['bankAccount'],'companyNum'=>$val['taxpayerID'], 'code' => $val['code'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 添加一行
     */
    public function addRow(): bool|string
    {
        $addIco = root . 'img/control/v_add.svg';
        $delIco = root . 'img/control/v_del.svg';
        $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)'  style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'title' => '', 'value' => '')) . "</select>";
        $mxId = suiji();
        $json['html'] = <<<eof
<tr class="tr-data td-data center">
  <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value=""><div class="add_v_btn"><img src="{$addIco}"></div><input id="$mxId" name="name[]" type="text" class="width_100"></td>
            <td><input name="model[]" type="text" class="width_100"></td>
            <td><input name="unit[]" type="text" class="width_100"></td>
            <td><input name="num[]" data-type="num" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td><input name="price[]" data-type="price" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td><input name="money[]" data-type="money" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$delIco}"></div></td>
      </tr>
<script>
        $("#{$mxId}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
             $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
eof;
        return json_encode($json, 320);
    }

    private function css()
    {
        $openObj = new openInvoiceClass();
        return $openObj->css();
    }


    /**
     * 模糊查询客户
     * @return bool|string
     */
    public function getClient(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $json['data'] = [];
        $where = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or code like '%" . $val . "%')";
        $all = find(array('table' => 'supplier', 'where' => "coid = '" . self::$coid . "' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array(
                'title' => $val['name'],
                'taxpayerID' => $val['taxpayerID'],
                'registeredAddress' => $val['registeredAddress'],
                'bankAccount' => $val['bankAccount'],
                'bankName' => $val['bankName'],
                'code' => $val['code'],
                'id' => $val['id']
            );
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }


    /**
     * 模糊查询员工
     */
    public function getStaff(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or orderNo like '%" . $val . "%')";
        $all = find(array('table' => 'staff', 'where' => "state != '离职' and workFlow = '已复核' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['name'], 'code' => $val['orderNo'], 'id' => $val['stid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }
    /**
     * 关联采购收货单
     * @return bool|string
     */
    public function addSendOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => L('finance.table.cgshdh'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('finance.table.dan_ju_ri_qi'))) .
            hidden(array('name'=>'supplierId','value'=>$this->post('khid'))).
            hidden(array('name'=>'id','value'=>$this->post('id'))).
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow('saleSendOrder')\" type='button' class='searchSub' value='".L('finance.table.ti_jiao')."'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('finance.table.tian_jia'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联采购收货单
     * @return bool|string
     */
    public function addSendOrderSearch(): bool|string
    {
        $supplierId = $this->post('supplierId');
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = " coid='" . self::$coid . "' and supplierId = '$supplierId' and id not in (select distinct orderId from purchase_get_order_detail where id in ('" . implode("','", $sourceId) . "'))";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' =>'已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "purchase_get_order",
            "where" => " {$where} ",
            'pageNum' => 50,
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("saleSendOrderForm", "saleSendOrderId");
        $tr[] = [$checkAll, L('finance.table.cgshdh'), L('finance.table.dan_ju_ri_qi')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "saleSendOrderId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='saleSendOrderForm'>" .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联采购收货单
     */
    public function addSendOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('saleSendOrderId');
        $id = $this->post('id');
        $isTax = $this->post('isTax');
        if (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('finance.table.qxzcgshd');
        } else {
            $json['html'] = '';
            foreach ($mxIdArr as $mxId) {
                $purchaseGetOrderMxAll = find(array('table' => "purchase_get_order as a join purchase_get_order_detail as b on a.id = b.orderId", 'where' => " a.id = '$mxId' order by list asc", 'field' => "b.*,a.orderNo"));
                foreach ($purchaseGetOrderMxAll['array'] as $purchaseGetOrderMx) {
                    $material = query('material', "id = '$purchaseGetOrderMx[materialId]'");
                    //已退货的数量
                    $refundNum = find(array(
                        'table' => 'purchase_refund_order_detail',
                        'where' => "orderId !='$id' and sourceId = '$purchaseGetOrderMx[id]' and coid = '" . self::$coid . "' and materialId = '$material[id]'",
                        'sum' => 'num'
                    ));
                    $num = ($purchaseGetOrderMx['num'] - $refundNum) > 0 ? ($purchaseGetOrderMx['num'] - $refundNum) : 0;
                    $price = $purchaseGetOrderMx['price'];
                    $moneyRes = saleOrderClass::isTax($num,$price, $purchaseGetOrderMx['rate'], $isTax);
                    $money = $moneyRes['money'];
                    $taxMoney = $moneyRes['taxMoney'];
                    $addIco = root . 'img/control/v_add.svg';
                    $delIco = root . 'img/control/v_del.svg';
                    $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)'  style='width: 80px;height: 22px'>" . option(array('value'=>$purchaseGetOrderMx['rate']*100,'option' => explode('，', para('taxRate')), 'title' => '',)) . "</select>";
                    $suiji = self::getId();
                    $name = materialClass::getName($material['id'],'*');
                    $json['html'] .= <<<efo
                  <tr class="tr-data td-data center">
                        <td>
                            <input name="mxId[]"  type="hidden" value="$suiji">
                            <input name="sourceId[]" type="hidden" value="$purchaseGetOrderMx[id]">
                            <div class="add_v_btn"><img src="{$addIco}"></div>
                            <input name="name[]" id="$suiji" value="$name" type="text" class="width_100">
                        </td>
                        <td><input name="model[]" value="$material[model]" type="text" class="width_100"></td>
                        <td><input name="unit[]" value="{$material['unit']}" type="text" class="width_100"></td>
                        <td><input name="num[]" data-type="num" value="$num" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td><input name="price[]" data-type="price" value="$price" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td><input name="money[]" data-type="money" value="$money" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td>$taxSelect</td>
                        <td><input name="taxMoney[]" value="$taxMoney" readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$delIco}"></div></td>
                  </tr>
<script>
        $("#{$suiji}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
              $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
efo;
                }
            }
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


}

